#ifndef C17304F1_55BF_48DC_A9ED_4315B375B2C2
#define C17304F1_55BF_48DC_A9ED_4315B375B2C2

#include<iostream>
#include"Log.hpp"
#include"socket.hpp"
#include"servercal.hpp"
#include<functional> 
#define  func_t function<string(string&)> 

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : port_(port), callback_(callback)
    {}
    ~TcpServer(){}

public:
    void Init()
    {
        listensockfd_.SocketInit();
        listensockfd_.Bind(port_);
        listensockfd_.Listen();
        lg(Info, "listen success");
    }

    void Start()
    {
        while (true)
        {
            //创建监听到的客户端的各种信息。 
            string clientip;
            uint16_t clientport;
            
            //创建字节流
            string str_istream;
            
            int sockfd = listensockfd_.Accpet(&clientip, &clientport);
            if (sockfd < 0)
            {
                continue;
            }
            lg(Info, "accept success, sockfd:%d, clientip:%s\n", sockfd, clientip.c_str());
            //提供服务
            if (fork() == 0)
            {
                //子程序， 提供服务
                listensockfd_.Close();
                while (true)
                {
                    //创建一个缓冲区
                    char buffer[128];
                    memset(buffer, 0, sizeof(buffer));
                    
                    //接收客户端的信息
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n <= 0) break;
                    else buffer[n] = 0;

                    //将缓冲区内容拷贝到字节流当中  
                    str_istream += buffer;
                    
                    //这里是日志信息debug
                    lg(Debug, "==========\ndebug:\n%s\n==================\n", str_istream.c_str());

                    //然后就对字符串进行处理，将处理后的结构返回给info  
                    string info = callback_(str_istream);
                    if (info == "") continue;  //返回的二
                                    
                    
                    //将得到的结果返回给客户端
                    write(sockfd, info.c_str(), info.size());
                }
                
            }

            exit(0);
        }

    }


private:
    func_t callback_;
    uint16_t port_;
    Socket listensockfd_;

};

#endif /* C17304F1_55BF_48DC_A9ED_4315B375B2C2 */
